package com.jianganming.netty.rpc.registry;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.apache.zookeeper.CreateMode;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class RegistryCenterWithZk {
    CuratorFramework curatorFramework =null;
    private String ip;
    private Integer port;

    public String getIp() {
        return ip;
    }

    public void setIp(String ip) {
        this.ip = ip;
    }

    public Integer getPort() {
        return port;
    }

    public void setPort(Integer port) {
        this.port = port;
    }

    public static RegistryCenterWithZk getRegistryCenterWithZk(){
        return new RegistryCenterWithZk();
    }

    private RegistryCenterWithZk(){
        curatorFramework = CuratorFrameworkFactory.builder().
                connectString("127.0.0.1:2181").sessionTimeoutMs(5000).
                retryPolicy(new ExponentialBackoffRetry(1000, 3))
                .namespace("registry")
                .build();
        curatorFramework.start();
    }

    public void registry(String serviceName, String serviceAddress) {
        String servicePath="/"+serviceName;
        try {
            //判断节点是否存在
            if(curatorFramework.checkExists().forPath(servicePath)==null){
                curatorFramework.create().creatingParentsIfNeeded().
                        withMode(CreateMode.PERSISTENT).forPath(servicePath);
            }
            //serviceAddress: ip:port
            String addressPath=servicePath+"/"+serviceAddress;
            if(curatorFramework.checkExists().forPath(addressPath)==null){
                curatorFramework.create().withMode(CreateMode.EPHEMERAL).forPath(addressPath);
                System.out.println("服务注册成功");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public RegistryCenterWithZk getData(String serviceName)throws Exception{
        String servicePath="/"+serviceName;
        List<String> strings = curatorFramework.getChildren().forPath(servicePath);
        if(!strings.isEmpty()){
            String s = strings.get(0);
            String[] split = s.split(":");
            ip = split[0];
            port = Integer.valueOf(split[1]);
        }
        return this;

    }
}
